package main

import (
	"database/sql"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"golang.org/x/crypto/bcrypt"
	"log"
	
)

const (
	username = "root"
	password = "root"
	hostname = "localhost:3306"
	dbname   = "entry_task"
)

func dsn(dbName string) string {
	return fmt.Sprintf("%s:%s@tcp(%s)/%s", username, password, hostname, dbName)
}

func createDatabase(db *sql.DB) {

	log.Printf("createDatabase start!")

	createDBQuery := fmt.Sprintf("CREATE DATABASE IF NOT EXISTS %s CHARACTER SET utf8 COLLATE utf8_bin",
		"entry_task")
	if _, err := db.Exec(createDBQuery); err != nil {
		log.Printf("Error %s when opening DB\n", err)
	}

	if _, err := db.Exec("USE " + "entry_task"); err != nil {
		log.Printf("Error %s when using DB\n", err)
	}

	query := `CREATE TABLE IF NOT EXISTS t_user` +
		`(user_id BIGINT UNSIGNED AUTO_INCREMENT NOT NULL,
					username VARCHAR(32) NOT NULL,
					password VARCHAR(64) NOT NULL,
					nickname VARCHAR(32) NOT NULL DEFAULT '', 
					profile_picture VARCHAR(160) NOT NULL DEFAULT '',
					created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
					updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
					PRIMARY KEY(user_id)
					) ENGINE = INNODB COLLATE utf8mb4_unicode_ci`
	_, err := db.Exec(query)
	if err != nil {
		log.Printf("Error %s when creating Table\n", err)
	}

	log.Printf("createDatabase end!")

}

func configureDatabase(db *sql.DB) {
	db.SetMaxOpenConns(151)
	db.SetMaxIdleConns(100)
}

// Generates password of length 16
func passwordGenerator() string {
	str := 123456
	return string(str)
}

func initDatabaseData(db *sql.DB) {
	num := 12
	for i := 1; i < 10000; i++ {

		log.Printf("")

		query := `INSERT INTO t_user (username, password, nickname, profile_picture) values `
		batch := 100
		for j := 1; j <= batch; j++ {
			num++
			username := fmt.Sprintf("user-%d", num)
			nickname := fmt.Sprintf("nickname-%d", num)
			password := passwordGenerator()
			log.Print(password)
			passwordHash, _ := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
			profilePicture := "resources/default.gif"
			row := fmt.Sprintf(`("%s", "%s", "%s", "%s")`, username, passwordHash, nickname, profilePicture)
			query = query + row
			if j < batch {
				query = query + `, `
			}
		}
		// log.Printf("sql is : %s", query)
		_, err := db.Exec(query)
		if err != nil {
			log.Printf("Error %s when inserting user\n", err)
		}
	}
}

func main() {
	db, err := sql.Open("mysql", dsn("mysql"))
	if err != nil {
		log.Printf("Error %s when opening DB\n", err)
	}
	createDatabase(db)
	configureDatabase(db)
	initDatabaseData(db)
}
